package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.constant.RedisConstant;
import com.itheima.dao.SetmealDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.Setmeal;
import com.itheima.service.SetmealService;
import com.sun.deploy.util.Waiter;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;
import redis.clients.jedis.JedisPool;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service(interfaceClass = SetmealService.class)
public class SetmealServiceImpl implements SetmealService {

    @Autowired
    private SetmealDao setmealDao;
    @Autowired
    private JedisPool jedisPool;
    @Autowired
    private FreeMarkerConfigurer freeMarkerConfigurer;
    @Value("${out_put_path}")
    private String outPutPath;

    // 添加
    public void add(Setmeal setmeal, Integer[] checkgroupIds) {
        setmealDao.add(setmeal);
        Integer setmealId = setmeal.getId();
        this.setSetmealAndCheckGroup(setmealId, checkgroupIds);
        String fileName = setmeal.getImg();
        jedisPool.getResource().sadd(RedisConstant.SETMEAL_PIC_DB_RESOURCES, fileName);

        generateMobileStaticHtml();

    }

    // 重新生成静态页面（套餐详情页面，套餐列表页面）
    public void generateMobileStaticHtml(){
        List<Setmeal> list = setmealDao.findAll();
        // 生成套餐列表页面
        generateMobileSetmealListHtml(list);
        // 生成套餐详情页面
        generateMobileSetmealDetailHtml(list);
    }

    // 生成套餐列表页面
    public void generateMobileSetmealListHtml(List<Setmeal> list){
        Map map = new HashMap();
        map.put("setmealList",list);
        generateHtml("mobile_setmeal.ftl","m_setmeal.html",map);
    }

    // 生成套餐详情页面
    public void generateMobileSetmealDetailHtml(List<Setmeal> list){
        for (Setmeal setmeal : list) {
            Map map = new HashMap();
            map.put("setmeal",setmealDao.findByIdJoin(setmeal.getId()));
            generateHtml("mobile_setmeal_detail.ftl","setmeal_detail_"+setmeal.getId()+".html",map);
        }
    }

    // 通用方法，生成静态套餐详情页面
    public void generateHtml(String templateName, String htmlPageName, Map map) {
        // 获取配置类
        Configuration configuration = freeMarkerConfigurer.getConfiguration();
        try {
            // 获取模板文件
            Template template = configuration.getTemplate(templateName);
            // 获取输出流
            Writer writer = new FileWriter(new File(outPutPath+"/"+htmlPageName));
            // 输出文件
            template.process(map,writer);
            writer.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 检查套餐与检查组之间的关系
    public void setSetmealAndCheckGroup(Integer setmealId, Integer[] checkgroupIds) {
        if (checkgroupIds != null && checkgroupIds.length > 0) {
            for (Integer checkgroupId : checkgroupIds) {
                Map<String, Integer> map = new HashMap<>();
                map.put("setmeal_Id", setmealId);
                map.put("checkgroup_Id", checkgroupId);
                setmealDao.setSetmealAndCheckGroup(map);
            }
        }
    }

    // 查询
    public PageResult findPageQuery(QueryPageBean queryPageBean) {
        Integer pageSize = queryPageBean.getPageSize();
        Integer currentPage = queryPageBean.getCurrentPage();
        String queryString = queryPageBean.getQueryString();

        PageHelper.startPage(currentPage, pageSize);

        Page<Setmeal> page = setmealDao.findPageQuery(queryString);
        return new PageResult(page.getTotal(), page.getResult());
    }

    // 客户端查询检查套餐
    public List<Setmeal> findAll() {
        return setmealDao.findAll();
    }

    // 套餐详情页面展示
    public Setmeal findById(Integer id) {
        Setmeal setmeal = setmealDao.findByIdJoin(id);
        return setmeal;
    }

 /*   public Setmeal findByIdJoin(Integer id) {
        Setmeal setmeal = setmealDao.findByIdJoin(id);
        return setmeal;
    }
*/
    // 页面回显检查组信息
    public List<Integer> findCheckGroupIds(Integer id) {
        return setmealDao.findCheckGroupIds(id);
    }

    // 编辑
    public void edit(Setmeal setmeal, Integer[] checkGroupIds) {
        setmealDao.edit(setmeal);
        Integer setmealId = setmeal.getId();
        // 清空检查组与套餐之间的关系
        setmealDao.deleteAssociation(setmealId);
        System.out.println(checkGroupIds[0]+".............");
        // 重新添加检查组与套餐之间的关系
        this.setSetmealAndCheckGroup(setmealId, checkGroupIds);
    }

    // 套餐查询
    public List<Map<String, Object>> findSetmealCount() {
        return setmealDao.findSetmealCount();
    }

}
